<?php
session_start();

// 检查用户是否已登录
if (!isset($_SESSION['username'])) {
    header('Content-Type: application/json');
    echo json_encode(['success' => false, 'message' => '请先登录']);
    exit();
}

$response = ['success' => false, 'message' => ''];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $old_password = $_POST['old_password'] ?? '';
    $new_password = $_POST['new_password'] ?? '';
    $confirm_password = $_POST['confirm_password'] ?? '';
    
    // 验证新密码
    if (strlen($new_password) < 6) {
        $response['message'] = '新密码长度不能少于6个字符';
    } elseif ($new_password !== $confirm_password) {
        $response['message'] = '两次输入的新密码不一致';
    } else {
        $users_file = 'users.json';
        if (file_exists($users_file)) {
            $users = json_decode(file_get_contents($users_file), true);
            if (is_array($users)) {
                foreach ($users as &$user) {
                    if ($user['username'] === $_SESSION['username']) {
                        if (password_verify($old_password, $user['password'])) {
                            $user['password'] = password_hash($new_password, PASSWORD_DEFAULT);
                            file_put_contents($users_file, json_encode($users, JSON_PRETTY_PRINT));
                            $response['success'] = true;
                            $response['message'] = '密码修改成功';
                        } else {
                            $response['message'] = '原密码错误';
                        }
                        break;
                    }
                }
            }
        }
    }
}

header('Content-Type: application/json');
echo json_encode($response); 